import axios from 'axios'
import qs from 'qs'
import { message } from 'ant-design-vue'
import { getCookie } from '@utils/cookie'
import { createBrowserHistory } from 'history'
const history = createBrowserHistory

// 创建实例定义默认配置
const request = axios.create({
  timeout: 8000
})

// axios.defaults.timeout = 8000
// 拦截器
// 请求拦截
let hide = null
request.interceptors.request.use(function (config) {
  hide = message.loading('加载中...', 2)
  if (getCookie()) {
    config.headers.token = getCookie()
  }
  if (config.method === 'post' || config.data) {
    config.data = qs.stringify(config.data)
  }
  return config
}, function (error) {
  hide()
  return Promise.reject(error)
})

// 响应拦截
request.interceptors.response.use(function (res) {
  hide()
  const errCode = [401, 403]
  if (errCode.includes(res.data.code)) {
    message.error('token过期或没有token', () => {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      history.push('/login')
      history.go(0)
    })
  }
  return res
}, function (error) {
  hide()
  return Promise.reject(error)
})

export default request
